import 'package:aitao_flutter/board/board_page.dart';
import 'package:aitao_flutter/chat/message_page.dart';
import 'package:aitao_flutter/common_ui/loading_view.dart';
import 'package:aitao_flutter/dynamic/dynamic_page.dart';
import 'package:aitao_flutter/home/views/home_page.dart';
import 'package:aitao_flutter/im/im_manager.dart';
import 'package:aitao_flutter/mine/views/mine_page.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';
import '../../const/common_const.dart';
import '../../res/r.dart';
import '../../style/text_style.dart';
import '../controller/CustomerTabController.dart';
import 'package:badges/badges.dart' as badges;

class Tabs extends StatefulWidget {
  const Tabs({Key? key}) : super(key: key);
  @override
  State<Tabs> createState() => _TabsState();
}

class _TabsState extends State<Tabs>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  //TabBarView 也可以  但是是 是TabController
  late PageController pageController;
  IMManager imManager = IMManager();
  List<Widget>? tabs;
  int currentIndex = 0;
  CustomerTabController controller = Get.put(CustomerTabController());
  @override
  Widget build(BuildContext context) {
    debugPrint('tab build....');
    return WillPopScope(
        onWillPop: () async {
          // AndroidBackTop.backDeskTop();
          return false;
        },
        child: Scaffold(
          bottomNavigationBar: ListenableBuilder(
            builder: (context, child) {
              debugPrint('tab ListenableBuilder....');
              return BottomNavigationBar(
                  currentIndex: currentIndex,
                  type: BottomNavigationBarType.fixed,
                  selectedItemColor: ColorStyle.themeColor,
                  unselectedItemColor: ColorStyle.normalTextColor,
                  onTap: (i) async {
                    if (i != currentIndex) {
                      currentIndex = i;
                      setState(() {});
                      pageController.jumpToPage(i);
                    }
                  },
                  items: [
                    BottomNavigationBarItem(
                      label: TabStringConst.homeText.tr,
                      icon: Image.asset(
                        currentIndex == 0
                            ? ImagePath.assetsImagesTabHomeSelect
                            : ImagePath.assetsImagesTabHomeUnSelect,
                        fit: BoxFit.fill,
                        // width: 24.w,
                        // height: 24.w,
                      ),
                    ),
                    BottomNavigationBarItem(
                      label: TabStringConst.dynamicText.tr,
                      icon: Image.asset(
                        currentIndex == 1
                            ? ImagePath.assetsImagesTabDynamicSelect
                            : ImagePath.assetsImagesTabDynamicUnSelect,
                        fit: BoxFit.fill,
                        // width: 24.w,
                        // height: 24.w,
                      ),
                    ),
                    BottomNavigationBarItem(
                      label: TabStringConst.boardText.tr,
                      icon: Image.asset(
                        currentIndex == 2
                            ? ImagePath.assetsImagesTabBoardSelect
                            : ImagePath.assetsImagesTabBoardUnSelect,
                        fit: BoxFit.fill,
                        // width: 24.w,
                        // height: 24.w,
                      ),
                    ),
                    BottomNavigationBarItem(
                      label: TabStringConst.messageText.tr,
                      icon: imManager.unReadCount == 0
                          ? Image.asset(
                              currentIndex == 3
                                  ? ImagePath.assetsImagesTabBoardSelect
                                  : ImagePath.assetsImagesTabBoardUnSelect,
                              fit: BoxFit.fill,
                              // width: 24.w,
                              // height: 24.w,
                            )
                          : badges.Badge(
                              position: badges.BadgePosition.topEnd(),
                              badgeStyle: const badges.BadgeStyle(
                                padding: EdgeInsets.all(6),
                              ),
                              badgeContent: Container(
                                // width: 15.w,
                                // height: 15.w,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    borderRadius: RadiusStyle.radiusAll(7.5),
                                    color: const Color(0xFFE94545)),
                                child: Text(
                                  imManager.unReadCount.toString(),
                                  style: const TextStyle(
                                      fontSize: 10, color: Colors.white),
                                ),
                              ),
                              child: Image.asset(
                                currentIndex == 3
                                    ? ImagePath.assetsImagesTabChatSelect
                                    : ImagePath.assetsImagesTabChatUnSelect,
                                fit: BoxFit.fill,
                                // width: 24.w,
                                // height: 24.w,
                              ),
                            ),
                    ),
                    BottomNavigationBarItem(
                      label: TabStringConst.mineText.tr,
                      icon: Image.asset(
                        currentIndex == 4
                            ? ImagePath.assetsImagesTabMineSelect
                            : ImagePath.assetsImagesTabMineUnSelect,
                        fit: BoxFit.fill,
                        // width: 24.w,
                        // height: 24.w,
                      ),
                    ),
                  ]);
            },
            listenable: imManager,
          ),
          body: tabs == null
              ? const LoadingView()
              : PageView(
                  //禁用横向滑动切换
                  physics: const NeverScrollableScrollPhysics(),
                  controller: pageController,
                  children: tabs!,
                ),
        )
        // bottomNavigationBar: BottomAppBar(
        //   shape: const CircularNotchedRectangle(),
        //   child: Row(
        //     mainAxisAlignment: MainAxisAlignment.spaceAround,
        //     children: [
        //       buildBotomItem(
        //           currentIndex,
        //           0,
        //           ImagePath.assetsImagesTabHomeSelect,
        //           ImagePath.assetsImagesTabHomeUnSelect,
        //           '首页',
        //           1),
        //       buildBotomItem(
        //           currentIndex,
        //           1,
        //           ImagePath.assetsImagesTabDynamicSelect,
        //           ImagePath.assetsImagesTabDynamicUnSelect,
        //           '动态',
        //           2),
        //       buildBotomItem(
        //           currentIndex,
        //           2,
        //           ImagePath.assetsImagesTabBoardSelect,
        //           ImagePath.assetsImagesTabBoardUnSelect,
        //           '榜单',
        //           0),
        //       buildBotomItem(
        //           currentIndex,
        //           3,
        //           ImagePath.assetsImagesTabChatSelect,
        //           ImagePath.assetsImagesTabChatUnSelect,
        //           '消息',
        //           unReadCount),
        //       buildBotomItem(
        //           currentIndex,
        //           4,
        //           ImagePath.assetsImagesTabMineSelect,
        //           ImagePath.assetsImagesTabMineUnSelect,
        //           '我的',
        //           0),
        //     ],
        //   ),
        // ),

        );
  }

  buildBotomItem(int selectIndex, int index, String normalIconString,
      String selectIconString, String title, int unreadCount) {
    //未选中状态的样式
    TextStyle textStyle = Styles.normalText_12;
    EdgeInsetsGeometry padding = const EdgeInsets.only(top: 6.0);
    if (selectIndex == index) {
      //选中状态的文字样式
      textStyle = Styles.mainText_12;
    }
    Widget padItem = const SizedBox();
    if (normalIconString.isNotEmpty) {
      padItem = Padding(
        padding: padding,
        child: Container(
          color: Colors.white,
          child: Center(
            child: Column(
              children: <Widget>[
                title == '消息'
                    ? Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Image.asset(
                            index != currentIndex
                                ? selectIconString
                                : normalIconString,
                            fit: BoxFit.fill,
                            // width: 24.w,
                            // height: 24.w,
                          ),
                          unreadCount == 0
                              ? Container()
                              : Positioned(
                                  right: -10,
                                  top: 0,
                                  child: unreadCount <= 0
                                      ? Container(
                                          width: 15.w,
                                          height: 15.w,
                                          alignment: Alignment.center,
                                        )
                                      : Container(
                                          width: 15.w,
                                          height: 15.w,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  RadiusStyle.radiusAll(7.5),
                                              color: const Color(0xFFE94545)),
                                          child: Text(
                                            unreadCount.toString(),
                                            style: const TextStyle(
                                                fontSize: 10,
                                                color: Colors.white),
                                          ),
                                        ),
                                )
                        ],
                      )
                    : Image.asset(
                        index != currentIndex
                            ? selectIconString
                            : normalIconString,
                        fit: BoxFit.fill,
                        // width: 24.w,
                        // height: 24.w,
                      ),
                Text(
                  title,
                  style: textStyle,
                )
              ],
            ),
          ),
        ),
      );
    }
    Widget item = Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {
          if (index != currentIndex) {
            setState(() {
              currentIndex = index;
            });
            pageController.jumpToPage(index);
          }
        },
        child: SizedBox(
          height: 52,
          child: padItem,
        ),
      ),
    );
    return item;
  }

  @override
  void initState() {
    tabs = [
      HomePage(),
      DynamicPage(),
      const BoardPage(),
      MessagePage(
        imManager: imManager,
      ),
      MinePage()
    ];
    pageController = PageController(initialPage: currentIndex, keepPage: true);
    super.initState();
    NimCore.instance.messageService.onMessage.listen((messages) {
      debugPrint('监听到消息');
      imManager.getIMUnReadCount();
    });
  }

  @override
  void dispose() {
    //记得要销毁哦
    pageController.dispose();
    super.dispose();
  }
}
